package com.siecom.tool;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.Base64;
import android.util.Log;

public class ImageUnit {

	public static Bitmap loadImageBinarization(String url, int w, int h) {

		return binarization(GetLocalOrNetBitmap(url), w, h);

	}

	public static Bitmap GetLocalOrNetBitmap(String url) {
		Bitmap imageBitmap = BitmapFactory.decodeFile(url);
		return imageBitmap;
	}


	public static Bitmap binarization(Bitmap img, int widthpix, int heightpix) {
		if(img==null){
			Log.e("img null","!!!!!");
			return null;
		}
		int width = img.getWidth();
		int height = img.getHeight();
		int area = width * height;
		int gray[][] = new int[width][height];
		int average = 0;// 灰度平均值
		int graysum = 0;
		int graymean = 0;
		int grayfrontmean = 0;
		int graybackmean = 0;
		int pixelGray;
		int front = 0;
		int back = 0;
		int[] pix = new int[width * height];
		img.getPixels(pix, 0, width, 0, 0, width, height);
		for (int i = 1; i < width; i++) { // 不算边界行和列，为避免越界
			for (int j = 1; j < height; j++) {
				int x = j * width + i;
				int r = (pix[x] >> 16) & 0xff;
				int g = (pix[x] >> 8) & 0xff;
				int b = pix[x] & 0xff;
				pixelGray = (int) (0.3 * r + 0.59 * g + 0.11 * b);// 计算每个坐标点的灰度
				gray[i][j] = (pixelGray << 16) + (pixelGray << 8) + (pixelGray);
				graysum += pixelGray;
			}
		}
		graymean = (int) (graysum / area);// 整个图的灰度平均值
		average = graymean;
		for (int i = 0; i < width; i++) // 计算整个图的二值化阈值
		{
			for (int j = 0; j < height; j++) {
				if (((gray[i][j]) & (0x0000ff)) < graymean) {
					graybackmean += ((gray[i][j]) & (0x0000ff));
					back++;
				} else {
					grayfrontmean += ((gray[i][j]) & (0x0000ff));
					front++;
				}
			}
		}
		int frontvalue = (int) (grayfrontmean / front);// 前景中心
		int backvalue = (int) (graybackmean / back);// 背景中心
		float G[] = new float[frontvalue - backvalue + 1];// 方差数组
		int s = 0;
		for (int i1 = backvalue; i1 < frontvalue + 1; i1++)// 以前景中心和背景中心为区间采用大津法算法（OTSU算法）
		{
			back = 0;
			front = 0;
			grayfrontmean = 0;
			graybackmean = 0;
			for (int i = 0; i < width; i++) {
				for (int j = 0; j < height; j++) {
					if (((gray[i][j]) & (0x0000ff)) < (i1 + 1)) {
						graybackmean += ((gray[i][j]) & (0x0000ff));
						back++;
					} else {
						grayfrontmean += ((gray[i][j]) & (0x0000ff));
						front++;
					}
				}
			}
			grayfrontmean = (int) (grayfrontmean / front);
			graybackmean = (int) (graybackmean / back);
			G[s] = (((float) back / area) * (graybackmean - average)
					* (graybackmean - average) + ((float) front / area)
					* (grayfrontmean - average) * (grayfrontmean - average));
			s++;
		}
		float max = G[0];
		int index = 0;
		for (int i = 1; i < frontvalue - backvalue + 1; i++) {
			if (max < G[i]) {
				max = G[i];
				index = i;
			}
		}

		for (int i = 0; i < width; i++) {
			for (int j = 0; j < height; j++) {
				int in = j * width + i;
				if (((gray[i][j]) & (0x0000ff)) < (index + backvalue)) {
					pix[in] = Color.rgb(0, 0, 0);
				} else {
					pix[in] = Color.rgb(255, 255, 255);
				}
			}
		}

		Bitmap temp = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		temp.setPixels(pix, 0, width, 0, 0, width, height);
		return resizeImage(temp, widthpix, heightpix);
	}
	public static Bitmap matrixCompress(Bitmap bmp,float size){
		Matrix matrix = new Matrix();
		matrix.setScale(size,size);
		return Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true);
	}
	public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
		Bitmap BitmapOrg = bitmap;
		
		int width = BitmapOrg.getWidth();
		int height = BitmapOrg.getHeight();
		
		if(width<w){
			return bitmap;
		}
		int newWidth = w;
		int newHeight = h;
		if ( width >= height)  
        {  
			newWidth = w;  
			newHeight = (int) Math.round((height * w * 1.0 / width));
        }  
        else   
        {  
        	newHeight = h;  
        	newWidth = (int) Math.round((width * h * 1.0 / height));
        }  
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
				height, matrix, true);
		return resizedBitmap;
	}
	/** 
	 * base64转为bitmap 
	 * @param base64Data 
	 * @return 
	 */  
	public static Bitmap base64ToBitmap(String base64Data) {
	    byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
	    return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}

	/**
	 * 背景色（指最终签名结果文件的背景颜色）
	 */
	private static int mBackColor = Color.WHITE;
	/**
	 * 逐行扫描 清楚边界空白。
	 *
	 * @param bp
	 * @param blank 边距留多少个像素
	 * @return
	 */
	public static Bitmap clearBlank(Bitmap bp, int blank) {
		int HEIGHT = bp.getHeight();
		int WIDTH = bp.getWidth();
		int top = 0, left = 0, right = 0, bottom = 0;
		int[] pixs = new int[WIDTH];
		boolean isStop;
		//扫描上边距不等于背景颜色的第一个点
		for (int y = 0; y < HEIGHT; y++) {
			bp.getPixels(pixs, 0, WIDTH, 0, y, WIDTH, 1);
			isStop = false;
			for (int pix : pixs) {
				if (pix != mBackColor) {
					top = y;
					isStop = true;
					break;
				}
			}
			if (isStop) {
				break;
			}
		}
		//扫描下边距不等于背景颜色的第一个点
		for (int y = HEIGHT - 1; y >= 0; y--) {
			bp.getPixels(pixs, 0, WIDTH, 0, y, WIDTH, 1);
			isStop = false;
			for (int pix : pixs) {
				if (pix != mBackColor) {
					bottom = y;
					isStop = true;
					break;
				}
			}
			if (isStop) {
				break;
			}
		}
		pixs = new int[HEIGHT];
		//扫描左边距不等于背景颜色的第一个点
		for (int x = 0; x < WIDTH; x++) {
			bp.getPixels(pixs, 0, 1, x, 0, 1, HEIGHT);
			isStop = false;
			for (int pix : pixs) {
				if (pix != mBackColor) {
					left = x;
					isStop = true;
					break;
				}
			}
			if (isStop) {
				break;
			}
		}
		//扫描右边距不等于背景颜色的第一个点
		for (int x = WIDTH - 1; x > 0; x--) {
			bp.getPixels(pixs, 0, 1, x, 0, 1, HEIGHT);
			isStop = false;
			for (int pix : pixs) {
				if (pix != mBackColor) {
					right = x;
					isStop = true;
					break;
				}
			}
			if (isStop) {
				break;
			}
		}
		if (blank < 0) {
			blank = 0;
		}
		//计算加上保留空白距离之后的图像大小
		left = left - blank > 0 ? left - blank : 0;
		top = top - blank > 0 ? top - blank : 0;
		right = right + blank > WIDTH - 1 ? WIDTH - 1 : right + blank;
		bottom = bottom + blank > HEIGHT - 1 ? HEIGHT - 1 : bottom + blank;
		return Bitmap.createBitmap(bp, left, top, right - left, bottom - top);
	}

	/**
	 * 图像二值化
	 * @param graymap
	 * @return
	 */
	public static Bitmap gray2Binary(Bitmap graymap) {

//得到图形的宽度和长度

		int width = graymap.getWidth();

		int height = graymap.getHeight();

//创建二值化图像

		Bitmap binarymap = null;

		binarymap = graymap.copy(Bitmap.Config.ARGB_8888, true);

//依次循环，对图像的像素进行处理

		for (int i = 0; i < width; i++) {

			for (int j = 0; j < height; j++) {

//得到当前像素的值

				int col = binarymap.getPixel(i, j);

//得到alpha通道的值

				int alpha = col & 0xFF000000;

//得到图像的像素RGB的值

				int red = (col & 0x00FF0000) >> 16;

				int green = (col & 0x0000FF00) >> 8;

				int blue = (col & 0x000000FF);

// 用公式X = 0.3×R+0.59×G+0.11×B计算出X代替原来的RGB

				int gray = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);

//对图像进行二值化处理

				if (gray <= 200) {

					gray = 0;

				} else {

					gray = 255;

				}

// 新的ARGB

				int newColor = alpha | (gray << 16) | (gray << 8) | gray;

//设置新图像的当前像素值

				binarymap.setPixel(i, j, newColor);

			}

		}

		return binarymap;

	}



}
